/*
 *  Copyright 2008-2011 NVIDIA Corporation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#pragma once

#include <thrust/detail/config.h>
#include <thrust/tuple.h>
#include <thrust/detail/type_traits.h>
#include <thrust/detail/allocator/zip_allocator.h>

namespace thrust
{
namespace detail
{

// in general, we just use the base Allocator for elements of type T
template<typename T, typename Alloc>
  class managed_layout_allocator
    : public Alloc
{};

template<typename Alloc,
         typename T0,
         typename T1,
         typename T2,
         typename T3,
         typename T4,
         typename T5,
         typename T6,
         typename T7,
         typename T8,
         typename T9>
  class managed_tuple_layout_allocator_base
{
  private:
    // name the tuple type
    typedef thrust::tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9> tuple_type;

    // a unary meta function which maps T -> managed layout allocator of T
    // with the appropriate base Allocator
    template<typename T>
      struct tuple_element_allocator
    {
      // make sure to rebind the allocator
      typedef managed_layout_allocator<T, typename Alloc::template rebind<T>::other> type;
    };

    // transform the tuple of elements into a tuple of managed allocators
    typedef typename thrust::detail::tuple_meta_transform<
      tuple_type,
      tuple_element_allocator
    >::type allocator_tuple;

  public:
    // the result is a zip_allocator
    typedef zip_allocator<allocator_tuple> type;
};

// XXX we could add a parameter to control the level
// of nesting that we want to expand

// specialization for tuple allocation
template<typename T0,
         typename T1,
         typename T2,
         typename T3,
         typename T4,
         typename T5,
         typename T6,
         typename T7,
         typename T8,
         typename T9,
         typename Alloc>
  class managed_layout_allocator<
          thrust::tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9>,
          Alloc
        >
    : public managed_tuple_layout_allocator_base<
               Alloc,T0,T1,T2,T3,T4,T5,T6,T7,T8,T9
             >::type
{};

} // end detail
} // end thrust

